//
//  PhotoSelectionView.m
//  XPhoto
//
//  Created by baboy on 2019/2/22.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "PhotoSelectionView.h"
#import "PHAsset+x.h"
#import "PhotoSelectionViewCell.h"
#import <BKKit/NSDate+x.h>
#import "PhotoLibPreviewViewController.h"
#import "BKNavigationController.h"

#define ITEM_MARGIN 5
#define NUM_OF_ROW 4
#define REUSE_CELL_ID @"photo_selection_view_cell"

@interface PhotoSelectionView()<PhotoSelectionViewCellDelegate,PhotoLibPreviewDelegate>{
    NSMutableArray<PHAsset*>* _selectedAssets;
}
@property(nonatomic, strong) PHFetchResult* photos;
@property(nonatomic, assign) CGSize itemSize;
@property(nonatomic, assign) BOOL shouldSelectPhoto;
@property(nonatomic, assign) BOOL shouldSelectVideo;
@end
@implementation PhotoSelectionView

- (void)awakeFromNib{
    [super awakeFromNib];
    self.selectionOneType = YES;
    self.maxSelectedCount = 36;
    self.maxVideoCount = -1;
    self.maxPhotoCount = -1;
    self.shouldSelectPhoto = YES;
    self.shouldSelectVideo = YES;
    [self setup];
}
- (void)setup{
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:[self collectViewFlowLayout]];
    [self.collectionView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
    self.collectionView.backgroundColor = self.backgroundColor;
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([PhotoSelectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:REUSE_CELL_ID];
    
    self.photos = [PHAsset fetchAllAssetsWithMediaType:PHAssetMediaTypeImage soryByCreationDateAsc:YES];
//    DLOG(@"photos:%@", self.photos);
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
//    [self.collectionView reloadData];
//    DLOG(@"photos:%@", self.photos);
    [self addSubview:self.collectionView];
    _selectedAssets = [NSMutableArray array];
}
- ( NSArray<PHAsset*>*) selectedAssets{
    return _selectedAssets;
}
- (void)resetFilterCondition{
    NSInteger n = self.selectedAssets.count;
    if (n >= self.maxSelectedCount) {
        self.shouldSelectPhoto = NO;
        self.shouldSelectVideo = NO;
        return;
    }
    NSInteger selectedVideoCount = 0;
    NSInteger selectedPhotoCount = 0;
    for (PHAsset *asset in self.selectedAssets) {
        if (asset.mediaType == PHAssetMediaTypeImage) {
            selectedPhotoCount ++;
        }
        if (asset.mediaType == PHAssetMediaTypeVideo) {
            selectedVideoCount ++;
        }
    }
    //只能选一种
    BOOL shouldSelectPhoto = YES;
    BOOL shouldSelectVideo = YES;
    if (self.selectionOneType) {
        shouldSelectPhoto = selectedPhotoCount > 0 || (selectedPhotoCount + selectedVideoCount) == 0;
        shouldSelectVideo = selectedVideoCount > 0 || (selectedPhotoCount + selectedVideoCount) == 0;
    }
    if (self.maxPhotoCount >= 0) {
        shouldSelectPhoto = shouldSelectPhoto && self.maxPhotoCount > selectedPhotoCount;
    }
    if (self.maxVideoCount >= 0) {
        shouldSelectVideo = shouldSelectVideo && self.maxVideoCount > selectedVideoCount;
    }
    BOOL reload = NO;
    if (self.shouldSelectPhoto != shouldSelectPhoto || self.shouldSelectVideo!=shouldSelectVideo) {
        reload = YES;
    }
    self.shouldSelectPhoto = shouldSelectPhoto;
    self.shouldSelectVideo = shouldSelectVideo;
    if (reload) {
        [self.collectionView reloadData];
    }
}
- (BOOL) shouldSelectAssetWithType:(PHAssetMediaType)mediaType{
    if (mediaType == PHAssetMediaTypeImage) {
        return self.shouldSelectPhoto;
    }
    if (mediaType == PHAssetMediaTypeVideo) {
        return self.shouldSelectVideo;
    }
    return NO;
}
/**
 * 指定类型是否只能选择一个
 */
- (BOOL) shouldSelectOnlyOneAssetWithType:(PHAssetMediaType)mediaType{
    if (mediaType == PHAssetMediaTypeImage) {
        return self.maxSelectedCount == 1 || self.maxPhotoCount == 1;
    }
    if (mediaType == PHAssetMediaTypeVideo) {
        return self.maxSelectedCount == 1 || self.maxVideoCount == 1;
    }
    return NO;
}
- (UICollectionViewFlowLayout*)collectViewFlowLayout{
    
    CGFloat itemWidth = (self.frame.size.width - (NUM_OF_ROW+1)*ITEM_MARGIN)/NUM_OF_ROW;
    
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = ITEM_MARGIN;
    flowLayout.minimumInteritemSpacing = ITEM_MARGIN;
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);;
//    flowLayout.sectionInset = UIEdgeInsetsMake(ITEM_MARGIN, ITEM_MARGIN,ITEM_MARGIN, ITEM_MARGIN);
    return flowLayout;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    
    CGFloat itemWidth = (self.frame.size.width - (NUM_OF_ROW+1)*ITEM_MARGIN)/NUM_OF_ROW;
    UICollectionViewFlowLayout * flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
}
- (BOOL)isSelected:(PHAsset *)asset{
    for (int i = 0; i<_selectedAssets.count; i++) {
        PHAsset *a = [_selectedAssets objectAtIndex:i];
        if([a.localIdentifier isEqualToString:asset.localIdentifier]){
            return YES;
        }
    }
    return NO;
}
- (BOOL)selectAsset:(PHAsset*)asset{
    //
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoSelectionView:shouldSelectPhoto:)]) {
        BOOL f = [self.delegate photoSelectionView:self shouldSelectPhoto:asset];
        if (!f) {
            return NO;
        }
    }
    //
    if (self.maxSelectedCount == 1) {
        [_selectedAssets removeAllObjects];
    }
    //
    if (!self.shouldSelectPhoto && !self.shouldSelectVideo) {
        return NO;
    }
    if ([self isSelected:asset]) {
        return NO;
    }
    [_selectedAssets addObject:asset];
    [self resetFilterCondition];
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(photoSelectionView:didSelectPhoto:)]){
        [self.delegate photoSelectionView:self didSelectPhoto:asset];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(photoSelectionView:didSelectPhotos:)]) {
        [self.delegate photoSelectionView:self didSelectPhotos:_selectedAssets];
    }
    return YES;
}
- (void)deselectAsset:(PHAsset*)asset{
    for (int i = 0; i<_selectedAssets.count; i++) {
        PHAsset *a = [_selectedAssets objectAtIndex:i];
        if([a.localIdentifier isEqualToString:asset.localIdentifier]){
            [_selectedAssets removeObjectAtIndex:i];
            if(self.delegate && [self.delegate respondsToSelector:@selector(photoSelectionView:didDeselectPhoto:)]){
                [self.delegate photoSelectionView:self didDeselectPhoto:a];
            }
            if (self.delegate && [self.delegate respondsToSelector:@selector(photoSelectionView:didSelectPhotos:)]) {
                [self.delegate photoSelectionView:self didSelectPhotos:_selectedAssets];
            }
            break;
        }
    }
    [self resetFilterCondition];
}
#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _photos.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PHAsset *asset = self.photos[indexPath.item];
    PhotoSelectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:REUSE_CELL_ID forIndexPath:indexPath];
    cell.delegate = self;
    cell.checkbox.selected = [self isSelected:asset];
    if (asset.mediaType == PHAssetMediaTypeVideo) {
        cell.durationLabel.text = [[NSDate dateWithTimeIntervalSince1970:asset.duration] format:@"mm:ss"];
        cell.durationLabel.hidden = NO;
    }
    //只能选择一个则不显示复选框
    if ([self shouldSelectOnlyOneAssetWithType:asset.mediaType]) {
        cell.checkbox.hidden = YES;
    }
    cell.maskView.hidden = [self shouldSelectAssetWithType:asset.mediaType];
    if (cell.checkbox.selected) {
        cell.maskView.hidden = YES;
    }

    CGSize itemSize = ((UICollectionViewFlowLayout*)collectionView.collectionViewLayout).itemSize;
#pragma mark - 单张缩略图
    [[PHCachingImageManager defaultManager] requestImageForAsset:asset
                                                      targetSize:itemSize contentMode:PHImageContentModeAspectFill
                                                         options:nil
                                                   resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                       
                                                       [cell.imageView setImage:result];
//                                                       DLOG(@"image info:%@", info);
                                                   }];
    cell.tag = indexPath.row;
    return cell;
}

#pragma mark- 单张图片
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    PHAsset *asset = self.photos[indexPath.item];
    PhotoLibPreviewViewController *vc = [[PhotoLibPreviewViewController alloc] init];
    vc.delegate = self;
    vc.currentIndex = indexPath.item;
    vc.photoCount = self.photos.count;
    vc.selectedPhotos = [NSMutableArray arrayWithArray:self.selectedAssets];
    [[(UIViewController *)self.delegate navigationController] pushViewController:vc animated:YES];
    
}
#pragma mark - PhotoSelectionViewCellDelegate
- (void)photoSelectionViewCellDidClickCheckbox:(PhotoSelectionViewCell *)cell{
    if ( cell.maskView.hidden ){
        PHAsset *asset = self.photos[cell.tag];
        if (!cell.checkbox.selected || self.maxSelectedCount == 1) {
            BOOL f = [self selectAsset:asset];
            if (f) {
                cell.checkbox.selected = YES;
            }
        }else{
            [self deselectAsset:asset];
            cell.checkbox.selected = NO;
        }
    }
}
#pragma mark - PhotoLibPreviewDelegate
- (PHAsset*)photoLibPreviewViewController:(PhotoLibPreviewViewController *)vc loadPhotoAtIndex:(NSInteger)index{
    return [self.photos objectAtIndex:index];
}
- (NSInteger)photoLibPreviewViewController:(PhotoLibPreviewViewController *)vc indexOfPhoto:(PHAsset *)photoAsset{
    return [self.photos indexOfObject:photoAsset];
}
- (BOOL)photoLibPreviewViewController:(PhotoLibPreviewViewController *)vc selectPhotoAtIndex:(NSInteger)index{
    PHAsset *asset = self.photos[index];
    BOOL ret = [self selectAsset:asset];
    if (ret) {
        [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    }
    return ret;
}
- (BOOL)photoLibPreviewViewController:(PhotoLibPreviewViewController *)vc deselectPhotoAtIndex:(NSInteger)index{
    PHAsset *asset = self.photos[index];
    [self deselectAsset:asset];
    [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    return YES;
}
- (BOOL)photoLibPreviewViewController:(PhotoLibPreviewViewController *)vc shouldSelectPhotoAtIndex:(NSInteger)index{
    PHAsset *photoAsset = [self.photos objectAtIndex:index];
    BOOL shouldSelect = [self shouldSelectAssetWithType:photoAsset.mediaType] || [self.selectedAssets indexOfObject:photoAsset] != NSNotFound;
    return shouldSelect;
}
- (void)photoLibPreviewViewControllerDidFinished:(PhotoLibPreviewViewController*)vc{
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
